<?php
class ModelCatalogLogcenter extends Model {
  public function addLogcenter($data) {
    if ($data['username1'] && empty($data['user_id'])) {
      $data['date_add'] = date('Y-m-d H:i:s');
      $data['store_url'] = $data['lat'] = $data['lng'] = '0';
      $Logcenter = M("Logcenters");
      $logcenter_id = $Logcenter->data($data)->add();
      
      $data2 = array(
        'user_group_id' => $data['user_group_id'],
        'fullname' => $data['firstname'],
        'username' => $data['username1'],
        'salt' => $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)),
        'password' => $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))),
        'email' => $this->db->escape($data['email']),
        'image' => $this->db->escape($data['logcenter_image']),
        'logcenter_permission' => (int)$logcenter_id,
        'store_permission' => (isset($data['product_store']) ? serialize($data['product_store']) : ''),
        'user_date_start' => !empty($data['user_date_start'])?$this->db->escape($data['user_date_start']):'0000-00-00',
        'user_date_end' => !empty($data['user_date_end'])?$this->db->escape($data['user_date_end']):'0000-00-00',
        'status' => (int)$data['status'],
        'code' => '0',
        'ip' => '0.0.0.0',
        'date_added' => date('Y-m-d H:i:s')
        );
      $User= M("User");
      $user_id = $User->data($data2)->add();

      $Logcenter->data(array('user_id'=>$user_id, 'logcenter_id'=>$logcenter_id))->save();

    } elseif (empty($data['username1']) && !empty($data['user_id'])) {
      $data['date_add'] = date('Y-m-d H:i:s');
      $data['store_url'] = $data['lat'] = $data['lng'] = '0';
      $Logcenter = M("Logcenters");
      $logcenter_id = $Logcenter->data($data)->add();

      $data2 = array(
        'user_group_id' => $data['user_group_id'],
        'logcenter_permission' => (int)$logcenter_id,
        'store_permission' => (isset($data['product_store']) ? serialize($data['product_store']) : ''),
        'user_date_start' => !empty($data['user_date_start'])?$this->db->escape($data['user_date_start']):'0000-00-00',
        'user_date_end' => !empty($data['user_date_end'])?$this->db->escape($data['user_date_end']):'0000-00-00',
        'status' => (int)$data['status'],
        'user_id' => (int)$this->db->escape($data['user_id'])
        );
      $User= M("User");
      $User->data($data2)->save();
      
      if ($data['password']) {
        $data2 = array(
          'salt' => $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)),
          'password' => $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))),
          'user_id' => (int)$this->db->escape($data['user_id'])
        );
        $User->data($data2)->save();
      }
    }
    
    if (0&&$data['email']) {
      $this->language->load('mail/signup');
      $mdata['title'] = sprintf($this->language->get('text_subject'), $this->config->get('config_name'));
      
      $mdata['text_message'] = sprintf($this->language->get('text_dear'), $data['firstname'] . ' ' . $data['lastname']) . ",<br /><br />";      
      $mdata['text_message'] .= sprintf($this->language->get('text_welcome1'), $this->config->get('config_name')) . "<br /><br />";
      $mdata['text_message'] .= $this->language->get('text_login') . "<br /><br />";
      
      if ($data['password']) {
        $mdata['text_message'] .= $this->language->get('text_info') . "<br />";
        
        if ($data['username']) {
          $username = $data['username'];
        } else {
          $username = $data['username1'];
        }
        
        $mdata['text_message'] .= $this->language->get('text_username') . $username . "<br />";
        $mdata['text_message'] .= $this->language->get('text_password') . $data['password'] . "<br />";
      }
      
      $mdata['text_message'] .= $this->language->get('text_url') . HTTP_SERVER . "<br /><br />";
      $mdata['text_message'] .= $this->language->get('text_services') . "<br /><br />";

      $mdata['text_message'] .= $this->language->get('text_thanks') . "<br />";
      $mdata['text_message'] .= $this->config->get('config_name');
      
      $mail = new Mail();
      $mail->protocol = $this->config->get('config_mail_protocol');
      $mail->parameter = $this->config->get('config_mail_parameter');
      $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
      $mail->smtp_username = $this->config->get('config_mail_smtp_username');
      $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
      $mail->smtp_port = $this->config->get('config_mail_smtp_port');
      $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
              
      $mail->setTo($data['email']);
      $mail->setFrom($this->config->get('config_email'));
      $mail->setSender($this->config->get('config_name'));
      $mail->setSubject(html_entity_decode($mdata['title'], ENT_QUOTES, 'UTF-8'));
      $mail->setHtml($this->load->view('mail/signup_notification.tpl', $mdata));
      $mail->send();
    }

    $this->cache->delete('logcenter');
  }

  public function editLogcenter($logcenter_id, $data) {
    $data['logcenter_id'] = (int)$logcenter_id;
    $Logcenter = M("Logcenters");
    $Logcenter->data($data)->save();
    
    //user account start
    $data2 = array(
      'user_group_id' => $data['user_group_id'],
      'fullname' => $data['firstname'],
      'email' => $this->db->escape($data['email']),
      'image' => $this->db->escape($data['logcenter_image']),
      'logcenter_permission' => (int)$logcenter_id,
      'cat_permission' => (isset($data['logcenter_category']) ? serialize($data['logcenter_category']) : ''),
      'store_permission' => (isset($data['product_store']) ? serialize($data['product_store']) : ''),
      'user_date_start' => !empty($data['user_date_start'])?$this->db->escape($data['user_date_start']):'0000-00-00',
      'user_date_end' => !empty($data['user_date_end'])?$this->db->escape($data['user_date_end']):'0000-00-00',
      'status' => (int)$data['status'],
      'user_id' =>  (int)$this->db->escape($data['user_id'])
    );
    if (isset($this->request->post['generate_path'])) {
      $data2['folder'] = (isset($this->request->post['generate_path']) ? $this->db->escape($data['username']) : '');
    } elseif (isset($this->request->post['remove_path'])) { 
      $data2['folder'] = (isset($this->request->post['remove_path']) ? '' : $this->db->escape($data['username']));  
    } else {
    }
    $User= M("User");
    $user_id = $User->data($data2)->save();
    
    if (0&&($data['status'] == '1') && ($data['pending_status'] == '5')) {
      $this->language->load('mail/signup');
      $subject = sprintf($this->language->get('text_subject'), $this->config->get('config_name'));
          
      $message = sprintf($this->language->get('text_welcome'), $this->config->get('config_name')) . "\n\n";
      $message .= $this->language->get('text_login') . "\n";
          
      $message .= HTTP_SERVER . "\n\n";
      $message .= $this->language->get('text_services') . "\n\n";
      $message .= $this->language->get('text_thanks') . "\n";
      $message .= $this->config->get('config_name');
  
      $mail = new Mail();
      $mail->protocol = $this->config->get('config_mail_protocol');
      $mail->parameter = $this->config->get('config_mail_parameter');
      $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
      $mail->smtp_username = $this->config->get('config_mail_smtp_username');
      $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
      $mail->smtp_port = $this->config->get('config_mail_smtp_port');
      $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
              
      $mail->setTo($data['email']);
      $mail->setFrom($this->config->get('config_email'));
      $mail->setSender($this->config->get('config_name'));
      $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
      $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
      $mail->send();
    }
    
    if ($data['password']) {
      $data2 = array(
          'salt' => $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)),
          'password' => $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))),
          'user_id' => (int)$this->db->escape($data['user_id'])
        );
      $User->data($data2)->save();
    }

    //增加超级与查看权限的物流中心账号
    $data3 = array();
    $data3['logcenter_permission'] = (int)$logcenter_id;
    $data3['user_group_id'] = $data['user_group_id'];
    if(!empty($data['super_user_id'])) {
      $data3['user_id'] = $data['super_user_id'];
      $data3['logcenter_permission_level'] = 1;
      $User->data($data3)->save();
    }
    if(!empty($data['normal_user_id'])) {
      $data3['user_id'] = $data['normal_user_id'];
      $data3['logcenter_permission_level'] = 2;
      $User->data($data3)->save();
    }
    //user account end

    $this->cache->delete('logcenter');
  }
  
  public function editLogcenterProfile($user_id, $data) {
    $sql = "UPDATE " . DB_PREFIX . "logcenters SET firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "', email = '" . $this->db->escape($data['email']) . "', paypal_email = '" . $this->db->escape($data['paypal_email']) . "', company_id = '" . $this->db->escape($data['company_id']) . "', iban = '" . $this->db->escape($data['iban']) . "', bank_name = '" . $this->db->escape($data['bank_name']) . "', bank_address = '" . $this->db->escape($data['bank_address']) . "', swift_bic = '" . $this->db->escape($data['swift_bic']) . "', tax_id = '" . $this->db->escape($data['tax_id']) . "',";
    
    if ($this->config->get('mvd_store_activated')) {
    $sql .= " accept_paypal = '" . $this->db->escape($data['accept_paypal']) . "', accept_cheques = '" . $this->db->escape($data['accept_cheques']) . "', accept_bank_transfer = '" . $this->db->escape($data['accept_bank_transfer']) . "',";
    }
    
    $sql .= " logcenter_description = '" . $this->db->escape($data['logcenter_description']) . "', address_1 = '" . $this->db->escape($data['address_1']) . "', address_2 = '" . $this->db->escape($data['address_2']) . "', city = '" . $this->db->escape($data['city']) . "', postcode = '" . $this->db->escape($data['postcode']) . "', country_id = '" . (int)$data['country_id'] . "', zone_id = '" . (int)$data['zone_id'] . "', store_url = '" . $this->db->escape($data['store_url']) . "' WHERE user_id = '" . (int)$user_id . "'";
    $query = $this->db->query($sql);
    
    if (isset($data['logcenter_image'])) {
      $this->db->query("UPDATE " . DB_PREFIX . "logcenters SET logcenter_image = '" . $this->db->escape($data['logcenter_image']) . "' WHERE user_id = '" . (int)$user_id . "'");
    }

    $this->cache->delete('logcenter');
  }
 
  public function deleteLogcenter($logcenter_id) {
    $this->db->query("DELETE FROM " . DB_PREFIX . "logcenters WHERE logcenter_id = '" . (int)$logcenter_id . "'");
    $this->db->query("DELETE FROM " . DB_PREFIX . "user WHERE logcenter_permission = '" . (int)$logcenter_id . "'");
  }
  
  public function getCommissionLimits() {
    $commission_data = array();
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "commission c LEFT JOIN " . DB_PREFIX . "product_limit pc ON (c.product_limit_id = pc.product_limit_id)");
    if ($query->rows) {
      $commission_text = '';
      foreach ($query->rows as $commission) {   
        if ($commission['commission_type'] == '0') {
          $commission_text = $commission['commission_name'] . ' (' . $commission['commission'] . '%) - ' . $commission['product_limit'];
        } elseif ($commission['commission_type'] == '1') { 
          $commission_text = $commission['commission_name'] . ' (' . $this->currency->format($commission['commission'], $this->config->get('config_currency')) . ') - ' . $commission['product_limit'];
        } elseif ($commission['commission_type'] == '2') {
          $dc = explode(':',$commission['commission']);
          $commission_text = $commission['commission_name'] . ' (' . $dc[0] . '% + ' . $dc[1] . ') - ' . $commission['product_limit'];
        } elseif ($commission['commission_type'] == '3') {
          $dc = explode(':',$commission['commission']);
          $commission_text = $commission['commission_name'] . ' (' . $dc[0] . ' + ' . $dc[1] . '%) - ' . $commission['product_limit'];
        } elseif ($commission['commission_type'] == '4') {
          $commission_text = $commission['commission_name'] . ' (' . $this->currency->format($commission['commission'], $this->config->get('config_currency')) . ') - ' . $commission['product_limit'];
        } elseif ($commission['commission_type'] == '5') { 
          $commission_text = $commission['commission_name'] . ' (' . $this->currency->format($commission['commission'], $this->config->get('config_currency')) . ') - ' . $commission['product_limit'];
        }
        
        $commission_data[] = array (
          'commission_id'   =>  $commission['commission_id'],
          'product_limit_id'  =>  $commission['product_limit_id'],
          'commission_name' =>  $commission['commission_name'],
          'commission_type' =>  $commission['commission_type'],
          'commission'    =>  $commission['commission'],
          'duration'      =>  $commission['duration'],
          'package_name'    =>  $commission['package_name'],
          'product_limit'   =>  $commission['product_limit'],
          'commission_text' =>  $commission_text,
          'sort_order'    =>  $commission['sort_order'],
          'date_add'      =>  $commission['date_add']
        );
      }
      return $commission_data;
    } else {
      return false; 
    }
  }
  
  public function getLogcenter($logcenter_id) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "logcenters WHERE logcenter_id = '" . (int)$logcenter_id . "'");
    if ($query->row) {
      $logcenter_info = $query->row;
      $logcenter_info['super_user_id'] = 0;
      $logcenter_info['normal_user_id'] = 0;
      $user_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "user WHERE logcenter_permission = '" . (int)$logcenter_id . "'");
      foreach ($user_query->rows as $user) {
        if($user['logcenter_permission_level'] == 1) {
          $logcenter_info['super_user_id'] = $user['user_id'];
        }
        if($user['logcenter_permission_level'] == 2) {
          $logcenter_info['normal_user_id'] = $user['user_id'];
        }
      }
      return $logcenter_info;
    } else {
      false;
    }
  }

  public function getLogcenterByName($name) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "logcenters WHERE logcenter_name = '" . $this->db->escape($name) . "'");
    if ($query->row) {
      $logcenter_info = $query->row;
      $logcenter_info['super_user_id'] = 0;
      $logcenter_info['normal_user_id'] = 0;
      $user_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "user WHERE logcenter_permission = '" . (int)$logcenter_id . "'");
      foreach ($user_query->rows as $user) {
        if($user['logcenter_permission_level'] == 1) {
          $logcenter_info['super_user_id'] = $user['user_id'];
        }
        if($user['logcenter_permission_level'] == 2) {
          $logcenter_info['normal_user_id'] = $user['user_id'];
        }
      }
      return $logcenter_info;
    } else {
      false;
    }
  }

  public function getLogcenterByUserId($user_id) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "logcenters WHERE user_id = '" . (int)$user_id . "'");
    if ($query->row) {
      return $query->row;
    } else {
      false;
    }
  }

  public function genPutInStockMsg($to_save_stock2) {
    $msg = '添加入库记录：<br>';
    foreach ($to_save_stock2 as $po_product_id => $qty) {
      $name = M('po_product')->where('id='.$po_product_id)->field(array('option_name', 'name'))->find();
      $name = ' -' . $name['name'] . '(' . $name['option_name'] . ')';
      $msg .= $name . ' : ' . $qty . '<br>';
    }
    return $msg;
  }

  public function genPutInStockInMsg($stockid,$to_save_stock2) {
    $msg = '生成入库单('.$stockid.')：<br>';
    foreach ($to_save_stock2 as $po_product_id => $qty) {
      $name = M('po_product')->where('id='.$po_product_id)->field(array('option_name', 'name'))->find();
      $name = ' -' . $name['name'] . '(' . $name['option_name'] . ')';
      $msg .= $name . ' : ' . $qty . '<br>';
    }
    return $msg;
  }
  
  public function getLogcenterProfile($user_id) {
    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "logcenters WHERE user_id = '" . (int)$user_id . "'");
    return $query->row; 
  }
  
  public function getLogcenters($data = array()) {
    
    if ($data) {
      $sql = "SELECT *,v.sort_order as vsort_order FROM " . DB_PREFIX . "logcenters v";
      $sql .= " LEFT JOIN " . DB_PREFIX . "user u ON (v.user_id = u.user_id)";
      
      if (isset($this->request->get['filter_status']) && !is_null($this->request->get['filter_status'])) {
        $sql .= " WHERE u.status = '" . (int)$this->request->get['filter_status'] . "'";
      }

      if (isset($data['filter_logcenter_name'])) {
        $sql .= " AND v.logcenter_name = '%" . $this->db->escape($data['filter_logcenter_name']) . "%'";
      } 

      $sort_data = array(
        'logcenter_name',
        'commission',
        'status'
      );

      if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
        $sql .= " ORDER BY " . $data['sort']; 
      } else {
        $sql .= " ORDER BY logcenter_name";  
      }
      
      if (isset($data['order']) && ($data['order'] == 'DESC')) {
        $sql .= " DESC";
      } else {
        $sql .= " ASC";
      }

      if (isset($data['start']) || isset($data['limit'])) {
        if ($data['start'] < 0) {
          $data['start'] = 0;
        }

        if ($data['limit'] < 1) {
          $data['limit'] = 20;
        }

        $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
      }

      $query = $this->db->query($sql);

      return $query->rows;
    } else {
      $logcenters_data = $this->cache->get('logcenter');
      if (!$logcenters_data) {
        $query = $this->db->query("SELECT *,v.sort_order as sort_order FROM " . DB_PREFIX . "logcenters v LEFT JOIN " . DB_PREFIX . "user u ON (v.user_id = u.user_id)");
      
        $logcenters_data = $query->rows;

        $this->cache->set('logcenter', $logcenters_data);
      }

      return $logcenters_data;
    }
  }
  public function getTotalLogcentersByLogcenterId($logcenters) {
        $query = $this->db->query("SELECT COUNT(logcenter) AS total FROM " . DB_PREFIX . "logcenter WHERE logcenter = '" . (int)$logcenters . "'");
    return $query->row['total'];
  }

  public function getTotalLogcenters($data = array()) {
    $sql = "SELECT COUNT(*) AS total FROM " . DB_PREFIX . "logcenters";
    $query = $this->db->query($sql);

    return $query->row['total'];
  }
  
  public function getByCountryZone($country_id,$zone_id) {
    $query = $this->db->query("SELECT zone FROM " . DB_PREFIX . "zone WHERE country_id = '" . (int)$country_id . "' AND zone_id = '" . (int)$zone_id . "'");
    
    return $query->row;
  }
  
  public function getLogcentersList($data = array()) {
    $sql = "SELECT logcenter_id,logcenter_name as name FROM " . DB_PREFIX . "logcenters ORDER BY logcenter_id" ;          
    $query = $this->db->query($sql);        
    return $query->rows;
  }
      
  Public function getUserAwaitingApproval($data = array()) {
    $query = $this->db->query("SELECT count(*) AS total FROM " . DB_PREFIX . "user u WHERE u.status = '5'");        
    return $query->row['total'];
  }
      
  Public function DisabledAllProducts($user_id) {
    $this->db->query("UPDATE " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "logcenter v ON (p.product_id = v.vproduct_id) LEFT JOIN " . DB_PREFIX . "logcenters vds ON (v.logcenter = vds.logcenter_id) LEFT JOIN " . DB_PREFIX . "user u ON (vds.user_id = u.user_id) SET p.status = '0' WHERE u.user_id = '" . (int)$this->db->escape($user_id) . "' AND p.status = '1'");
  }
      
  Public function EnabledAllProducts($user_id) {
    $this->db->query("UPDATE " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "logcenter v ON (p.product_id = v.vproduct_id) LEFT JOIN " . DB_PREFIX . "logcenters vds ON (v.logcenter = vds.logcenter_id) LEFT JOIN " . DB_PREFIX . "user u ON (vds.user_id = u.user_id) SET p.status = '1' WHERE u.user_id = '" . (int)$this->db->escape($user_id) . "' AND p.status = '0'");
  }
  
  public function getUsers($data = array()) {
    $sql = "SELECT * FROM `" . DB_PREFIX . "user`";
    
    //mvds
    if (isset($this->request->get['filter_status']) && !is_null($this->request->get['filter_status'])) {
      $sql .= " WHERE status = '" . (int)$this->request->get['filter_status'] . "'";
    }
    //mvde
    
    $sort_data = array(
      'username',
      'status',
      'date_added'
    );

    if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
      $sql .= " ORDER BY " . $data['sort'];
    } else {
      $sql .= " ORDER BY username";
    }

    if (isset($data['order']) && ($data['order'] == 'DESC')) {
      $sql .= " DESC";
    } else {
      $sql .= " ASC";
    }

    if (isset($data['start']) || isset($data['limit'])) {
      if ($data['start'] < 0) {
        $data['start'] = 0;
      }

      if ($data['limit'] < 1) {
        $data['limit'] = 20;
      }

      $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
    }

    $query = $this->db->query($sql);

    return $query->rows;
  }

  public function getTotalUsers() {
    //$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "user`");
    //mvds
    $sql = "SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "user`";
    if (isset($this->request->get['filter_status']) && !is_null($this->request->get['filter_status'])) {
      $sql .= " WHERE status = '" . (int)$this->request->get['filter_status'] . "'";
    }
    $query = $this->db->query($sql);
    //mvde
    return $query->row['total'];
  }
  
  public function ValidateUserMapping($user_id) {   
    $query = $this->db->query("SELECT count(*) AS total FROM " . DB_PREFIX . "logcenters WHERE user_id = '" . (int)$user_id . "'");        
    return $query->row['total'];
  }

    public function getAvailableLogcenters (){
        $sql = "SELECT `logcenter_id`,`logcenter_name` FROM `".DB_PREFIX."logcenters` WHERE `default_warehouse` IN (SELECT `warehouse_id` FROM `warehouse` WHERE `status`=1) ORDER BY `logcenter_id` ASC";
        $query = $this->db->query($sql);
        return $query->rows;
    }
}
?>